﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Text;
using SystemSettings;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.Setting;
using Labthink.PCSoft.UniversalHost4.Model.User;
using Labthink.PCSoft.UniversalHost4.Utility;
using NLog;

namespace Labthink.PCSoft.UniversalHost4.DataAccess
{
    /// <summary>
    /// 用户
    /// </summary>
    public class UserRepository : BaseRepository
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 判断用户登录名是否存在
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public static bool Exists(string loginName)
        {
            IsDbExist();
            var r = SqliteHelper.ExecuteScalar(DbFile, "SELECT COUNT(1) FROM User WHERE LoginName=@LoginName", loginName);
            if (r == null) return false;
            return r.ToInt32() > 0;
        }

        /// <summary>
        /// 根据用户ID获取用户信息 
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public static UserInfo GetUser(int uid)
        {
            IsDbExist();
            Log.Debug("根据用户ID获取用户信息：{0}", uid);
            var ds = SqliteHelper.ExecuteDataSet(DbFile, "SELECT * FROM ViewUser WHERE Id=@uid ", new object[] { uid });
            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            {
                Log.Debug("用户名 {0} 不存在", uid);
                return null;
            }

            var dr = ds.Tables[0].Rows[0];
            var u = new UserInfo
            {
                Id = dr["Id"].ToInt32(),
                Barcode = dr["Barcode"].ToString(),
                Birth = dr["Birth"].ToDateTime(),
                Email = dr["Email"].ToString(),
                ExpiresDate = dr["ExpiresDate"].ToDateTime(),
                LockDate = dr["LockDate"].ToDateTime(),
                Gender = dr["Gender"].ToInt32(),
                IsDelete = dr["IsDelete"].ToBool(),
                IsFirst = dr["IsFirst"].ToBool(),
                IsLock = dr["IsLock"].ToBool(),
                LastDate = dr["LastDate"].ToDateTime(),
                Salt = dr["Salt"].ToString(),
                UserName = dr["UserName"].ToString(),
                LoginName = dr["LoginName"].ToString(),
                Password = "******",
                Phone = dr["Phone"].ToString(),
                Role = dr["Role"].ToInt32(),
                RoleName = dr["RoleName"].ToString(),
                LastErrorDate = dr["LastErrorDate"].ToDateTime(),
                Creator = dr["Creator"].ToString(),
                CreateDate = dr["CreateDate"].ToDateTime(),
                DeleteDate = dr["DeleteDate"].ToDateTime()
            };

            return u;
        }

        /// <summary>
        /// 根据用户登录名获取用户信息 
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public static UserInfo GetUserByLoginName(string loginName)
        {
            IsDbExist();
            Log.Debug("根据用户登录名获取用户信息：{0}", loginName);
            var ds = SqliteHelper.ExecuteDataSet(DbFile, "SELECT * FROM ViewUser WHERE LoginName=@LoginName ",
                new[] { loginName });
            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            {
                Log.Debug("用户名 {0} 不存在", loginName);
                return null;
            }

            var dr = ds.Tables[0].Rows[0];
            var u = new UserInfo
            {
                Id = dr["Id"].ToInt32(),
                Barcode = dr["Barcode"].ToString(),
                Birth = dr["Birth"].ToDateTime(),
                Email = dr["Email"].ToString(),
                ExpiresDate = dr["ExpiresDate"].ToDateTime(),
                LockDate = dr["LockDate"].ToDateTime(),
                Gender = dr["Gender"].ToInt32(),
                IsDelete = dr["IsDelete"].ToInt32() > 0,
                IsFirst = dr["IsFirst"].ToInt32() > 0,
                IsLock = dr["IsLock"].ToInt32() > 0,
                LastDate = dr["LastDate"].ToDateTime(),
                Salt = dr["Salt"].ToString(),
                UserName = dr["UserName"].ToString(),
                LoginName = loginName,
                Password = dr["Password"].ToString(),
                Phone = dr["Phone"].ToString(),
                Role = dr["Role"].ToInt32(),
                RoleName = dr["RoleName"].ToString(),
                LastErrorDate = dr["LastErrorDate"].ToDateTime(),
                Creator = dr["Creator"].ToString(),
                CreateDate = dr["CreateDate"].ToDateTime(),
                DeleteDate = dr["DeleteDate"].ToDateTime()
            };

            return u;
        }

        /// <summary>
        /// 查询所有的用户信息
        /// </summary>
        /// <returns></returns>
        public static List<UserInfo> GetUser()
        {
            IsDbExist();
            Log.Debug("获取全部用户信息");
            var users = new List<UserInfo>();
            try
            {
                var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(DbFile));
                con.Open();
                var cmd = con.CreateCommand();
                var reader = SqliteHelper.ExecuteReader(cmd, "SELECT * FROM ViewUser WHERE IsDelete=0", null);
                while (reader.Read())
                {
                    users.Add(new UserInfo
                    {
                        Id = reader["Id"].ToInt32(),
                        Barcode = reader["Barcode"].ToString(),
                        Birth = reader["Birth"].ToDateTime(),
                        Email = reader["Email"].ToString(),
                        ExpiresDate = reader["ExpiresDate"].ToDateTime(),
                        LockDate = reader["LockDate"].ToDateTime(),
                        Gender = reader["Gender"].ToInt32(),
                        IsDelete = reader["IsDelete"].ToInt32() > 0,
                        IsFirst = reader["IsFirst"].ToInt32() > 0,
                        IsLock = reader["IsLock"].ToInt32() > 0,
                        Salt = reader["Salt"].ToString(),
                        LastDate = reader["LastDate"].ToDateTime(),
                        UserName = reader["UserName"].ToString(),
                        LoginName = reader["LoginName"].ToString(),
                        Password = "******",
                        Phone = reader["Phone"].ToString(),
                        Role = reader["Role"].ToInt32(),
                        RoleName = reader["RoleName"].ToString(),
                        LastErrorDate = reader["LastErrorDate"].ToDateTime(),
                        Creator = reader["Creator"].ToString(),
                        CreateDate = reader["CreateDate"].ToDateTime(),
                        DeleteDate = reader["DeleteDate"].ToDateTime()
                    });
                }

                reader.Close();
            }
            catch (Exception e)
            {
                Log.Error(e,"查询所有用户出错");
            }

            return users;
        }

        /// <summary>
        /// 根据名称查找用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static List<UserInfo> GetUser(string userName)
        {
            IsDbExist();
            Log.Debug("根据用户名{0}获取用户信息", userName);
            var users = new List<UserInfo>();
            try
            {
                var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(DbFile));
                con.Open();
                var cmd = con.CreateCommand();
                var reader = SqliteHelper.ExecuteReader(cmd,
                    "SELECT * FROM ViewUser WHERE IsDelete=0 AND (UserName LIKE @UserName OR LoginName LIKE @LoginName)",
                    new object[] { "%" + userName + "%", "%" + userName + "%" });
                while (reader.Read())
                {
                    users.Add(new UserInfo
                    {
                        Id = reader["Id"].ToInt32(),
                        Barcode = reader["Barcode"].ToString(),
                        Birth = reader["Birth"].ToDateTime(),
                        Email = reader["Email"].ToString(),
                        ExpiresDate = reader["ExpiresDate"].ToDateTime(),
                        LockDate = reader["LockDate"].ToDateTime(),
                        Gender = reader["Gender"].ToInt32(),
                        IsDelete = reader["IsDelete"].ToInt32() > 0,
                        IsFirst = reader["IsFirst"].ToInt32() > 0,
                        IsLock = reader["IsLock"].ToInt32() > 0,
                        Salt = reader["Salt"].ToString(),
                        LastDate = reader["LastDate"].ToDateTime(),
                        UserName = reader["UserName"].ToString(),
                        LoginName = reader["LoginName"].ToString(),
                        Password = "******",
                        Phone = reader["Phone"].ToString(),
                        Role = reader["Role"].ToInt32(),
                        RoleName = reader["RoleName"].ToString(),
                        LastErrorDate = reader["LastErrorDate"].ToDateTime(),
                        Creator = reader["Creator"].ToString(),
                        CreateDate = reader["CreateDate"].ToDateTime(),
                        DeleteDate = reader["DeleteDate"].ToDateTime()
                    });
                }

                reader.Close();
            }
            catch (Exception e)
            {
                Log.Error(e,"根据用户名查询用户出错");
            }

            return users;
        }

        /// <summary>
        /// 根据查询条件获取用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="role"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public static PagedList<UserInfo> GetUser(string userName, int? role, int pageIndex, int pageCount)
        {
            IsDbExist();
            Log.Debug("根据查询条件获取用户信息");
            var users = new List<UserInfo>();
            if (pageIndex == 0) pageIndex = 1;
            if (pageIndex <= 0 || pageCount <= 0)
            {
                return null;
            }

            var sql = new StringBuilder("SELECT * FROM ViewUser WHERE Role >2 ");
            var sqlCount = new StringBuilder("SELECT COUNT(1) FROM ViewUser  WHERE Role >2");
            var objs = new List<object>();
            if (!string.IsNullOrEmpty(userName))
            {
                sql.Append(" AND  (UserName LIKE @UserName OR LoginName LIKE @LoginName) ");
                sqlCount.Append(" AND  (UserName LIKE @UserName OR LoginName LIKE @LoginName) ");
                objs.Add("%" + userName + "%");
                objs.Add("%" + userName + "%");
            }

            if (role != null)
            {
                sql.Append(" AND Role=@Role");
                sqlCount.Append(" AND Role=@Role");
                objs.Add(role.Value);
            }

            sql.Append(" ORDER BY Id DESC LIMIT " + (pageIndex - 1) * pageCount + "," + pageCount);
            int count;
            try
            {
                var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(DbFile));
                con.Open();
                var cmd = con.CreateCommand();
                var reader = SqliteHelper.ExecuteReader(cmd, sql.ToString(), objs.ToArray());
                while (reader.Read())
                {
                    users.Add(new UserInfo
                    {
                        Id = reader["Id"].ToInt32(),
                        Barcode = reader["Barcode"].ToString(),
                        Birth = reader["Birth"].ToDateTime(),
                        Email = reader["Email"].ToString(),
                        ExpiresDate = reader["ExpiresDate"].ToDateTime(),
                        LockDate = reader["LockDate"].ToDateTime(),
                        Gender = reader["Gender"].ToInt32(),
                        IsDelete = reader["IsDelete"].ToInt32() > 0,
                        IsFirst = reader["IsFirst"].ToInt32() > 0,
                        IsLock = reader["IsLock"].ToInt32() > 0,
                        LastDate = reader["LastDate"].ToDateTime(),
                        UserName = reader["UserName"].ToString(),
                        LoginName = reader["LoginName"].ToString(),
                        Salt = reader["Salt"].ToString(),
                        Password = "******",
                        Phone = reader["Phone"].ToString(),
                        Role = reader["Role"].ToInt32(),
                        RoleName = reader["RoleName"].ToString(),
                        LastErrorDate = reader["LastErrorDate"].ToDateTime(),
                        Creator = reader["Creator"].ToString(),
                        CreateDate = reader["CreateDate"].ToDateTime(),
                        DeleteDate = reader["DeleteDate"].ToDateTime()
                    });
                }

                reader.Close();
                if (con.State != ConnectionState.Open) con.Open();
                try
                {
                    count = SqliteHelper.ExecuteScalar(DbFile, sqlCount.ToString(), objs.ToArray()).ToInt32();
                }
                catch (Exception e)
                {
                    Log.Error("获取用户总数出错:{0}", e, sqlCount.ToString());
                    return null;
                }
            }
            catch (Exception e)
            {
                Log.Error("根据查询条件查询用户信息出错:{0}", e, sql);
                return null;
            }

            return new PagedList<UserInfo>(users)
            {
                TotalCount = count,
                PageIndex = pageIndex,
                PageSize = users.Count,
                PageCount = (int)Math.Ceiling((double)count / pageCount)
            };
        }

        /// <summary>
        /// 添加新用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static int AddUser(UserInfo user)
        {
            IsDbExist();
            SafeInfo safeInfo = ConfigAndSettings.GetSafeInfo();
            if (Exists(user.LoginName))
                throw new BusinessException(LanguageManager.GetLanguageValue("SD-UserExist",user.LoginName));

            Log.Debug("添加一位新用户：{0}", user.UserName);
            using var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(DbFile));
            con.Open();
            var tran = con.BeginTransaction();
            var baseCmd = con.CreateCommand();
            var salt = Guid.NewGuid().ToString();
            string pwd = PasswordHash.HashPassword(safeInfo.DefaultPassword, salt);
            baseCmd.CommandText =
                "INSERT INTO User (UserName,LoginName,Password,Salt,Gender,Birth,Email,Phone,Role) VALUES (@UserName,@LoginName,@Password,@Salt,@Gender,@Birth,@Email,@Phone,@Role)";
            baseCmd.Parameters.Add(new SQLiteParameter("@UserName", user.UserName));
            baseCmd.Parameters.Add(new SQLiteParameter("@LoginName", user.LoginName));
            baseCmd.Parameters.Add(new SQLiteParameter("@Password", pwd));
            baseCmd.Parameters.Add(new SQLiteParameter("@Salt", salt));
            baseCmd.Parameters.Add(new SQLiteParameter("@Gender", user.Gender));
            baseCmd.Parameters.Add(new SQLiteParameter("@Birth", null));
            baseCmd.Parameters.Add(new SQLiteParameter("@Email", user.Email));
            baseCmd.Parameters.Add(new SQLiteParameter("@Phone", user.Phone));
            baseCmd.Parameters.Add(new SQLiteParameter("@Role", user.Role));
            var extendCmd = con.CreateCommand();
            extendCmd.CommandText =
                "INSERT INTO UserExtend (LoginName,Barcode,LastDate,ExpiresDate,LockDate,LastErrorDate,Creator,CreateDate,DeleteDate) VALUES (@LoginName,@Barcode,@LastDate,@ExpiresDate,@LockDate,@LastErrorDate,@Creator,@CreateDate,@DeleteDate)";
            extendCmd.Parameters.Add(new SQLiteParameter("@LoginName", user.LoginName));
            extendCmd.Parameters.Add(new SQLiteParameter("@Creator", user.Creator));
            extendCmd.Parameters.Add(new SQLiteParameter("@CreateDate", DateTime.Now));
            extendCmd.Parameters.Add(new SQLiteParameter("@DeleteDate", null));
            extendCmd.Parameters.Add(new SQLiteParameter("@Barcode", user.Barcode));

            // UserExtend表定义中已经设置默认值
            //extendCmd.Parameters.Add(new SQLiteParameter("@IsFirst", 1));
            //extendCmd.Parameters.Add(new SQLiteParameter("@IsLock", 0));
            //extendCmd.Parameters.Add(new SQLiteParameter("@IsDelete",  0));
            extendCmd.Parameters.Add(new SQLiteParameter("@LastDate", null));
            extendCmd.Parameters.Add(new SQLiteParameter("@ExpiresDate", DateTime.MaxValue));
            extendCmd.Parameters.Add(new SQLiteParameter("@LockDate", null));
            extendCmd.Parameters.Add(new SQLiteParameter("@LastErrorDate", null));
            try
            {
                SqliteHelper.ExecuteNonQuery(tran, baseCmd);
                SqliteHelper.ExecuteNonQuery(tran, extendCmd);
                tran.Commit();
            }
            catch (Exception e)
            {
                Log.Error("添加新用户失败:{0} / {1}", e, "INSERT INTO User (UserName,LoginName,Password,Salt,Gender,Birth,Email,Phone,Role) VALUES (@UserName,@LoginName,@Password,@Salt,@Gender,@Birth,@Email,@Phone,@Role)", "INSERT INTO UserExtend (LoginName,Barcode,IsFirst,LastDate,ExpiresDate,LockDate,IsLock,IsDelete,LastErrorDate,Creator,CreateDate,DeleteDate) VALUES (@LoginName,@Barcode,@IsFirst,@LastDate,@ExpiresDate,@LockDate,@IsLock,@IsDelete,@LastErrorDate,@@Creator,@CreateDate,@DeleteDate)");
                throw new BusinessException(LanguageManager.GetLanguageValue("ActionFail"));
            }

            return 0;
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static int UpdateUser(UserInfo user)
        {
            IsDbExist();
            Log.Debug(" 修改用户{0}的信息", user.UserName);
            using var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(DbFile));
            con.Open();
            var tran = con.BeginTransaction();
            var baseCmd = con.CreateCommand();
            baseCmd.CommandText =
                "UPDATE User SET UserName=@UserName,Gender=@Gender,Birth=@Birth,Email=@Email,Phone=@Phone,Role=@Role WHERE Id=@Id";
            baseCmd.Parameters.Add(new SQLiteParameter("@UserName", user.UserName));
            baseCmd.Parameters.Add(new SQLiteParameter("@Gender", user.Gender));
            baseCmd.Parameters.Add(new SQLiteParameter("@Birth", user.Birth));
            baseCmd.Parameters.Add(new SQLiteParameter("@Email", user.Email));
            baseCmd.Parameters.Add(new SQLiteParameter("@Phone", user.Phone));
            baseCmd.Parameters.Add(new SQLiteParameter("@Role", user.Role));
            baseCmd.Parameters.Add(new SQLiteParameter("@Id", user.Id));

            try
            {
                SqliteHelper.ExecuteNonQuery(tran, baseCmd);
                tran.Commit();
            }
            catch (Exception e)
            {
                Log.Error("修改用户信息失败:{0}", e, "UPDATE User SET UserName=@UserName,Gender=@Gender,Birth=@Birth,Email=@Email,Phone=@Phone,Role=@Role WHERE Id=@Id");
                throw new BusinessException(LanguageManager.GetLanguageValue("Failure_ModifyUser"));
            }

            return 0;
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public static int ResetPassword(string loginName)
        {
            IsDbExist();
            SafeInfo safeInfo = ConfigAndSettings.GetSafeInfo();
            string salt = GetSalt(loginName);
            string pwd = PasswordHash.HashPassword(safeInfo.DefaultPassword, salt);
            const string sql = "UPDATE User SET Password=@Password WHERE LoginName=@LoginName";
            Log.Debug("重置用户{0} 的密码", loginName);
            using var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(DbFile));
            con.Open();
            SQLiteTransaction tran = con.BeginTransaction();
            try
            {
                SqliteHelper.ExecuteNonQuery(tran, sql, pwd, loginName);
                SqliteHelper.ExecuteNonQuery(tran, "UPDATE UserExtend SET IsFirst=1 WHERE LoginName=@LoginName",
                    loginName);
                tran.Commit();
                return 0;
            }
            catch (Exception e)
            {
                tran.Rollback();
                Log.Error("重置密码失败:{0}", e, sql);
                throw  new BusinessException(LanguageManager.GetLanguageValue("ActionFail"));
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="newPwd"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public static int ChangePassword(string loginName, string newPwd, int month)
        {
            IsDbExist();
            UserInfo u = GetUserByLoginName(loginName);

            string newHashPassword = PasswordHash.HashPassword(newPwd, u.Salt);
            const string sql = "UPDATE User SET Password=@Password WHERE LoginName=@LoginName";
            Log.Debug("修改用户 {0} 的密码", u.UserName);
            using var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(DbFile));
            con.Open();
            SQLiteTransaction tran = con.BeginTransaction();
            try
            {
                SqliteHelper.ExecuteNonQuery(tran, sql, newHashPassword, loginName);
                SqliteHelper.ExecuteNonQuery(tran, "UPDATE UserExtend SET ExpiresDate=@ExpiresDate,IsFirst=0 WHERE LoginName=@LoginName", month > 0 ? DateTime.Now.AddMonths(month) : DateTime.MaxValue, loginName);
                tran.Commit();
                return 0;
            }
            catch (Exception e)
            {
                tran.Rollback();
                Log.Error("修改密码失败:{0}", e, sql);
                throw new BusinessException(LanguageManager.GetLanguageValue("ActionFail"));
            }
        }

        /// <summary>
        /// 锁定解锁用户
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="isLock"></param>
        /// <returns></returns>
        public static int LockUser(string loginName, bool isLock)
        {
            IsDbExist();
            try
            {
                return SqliteHelper.ExecuteNonQuery(DbFile,
                    "UPDATE UserExtend SET IsLock=@IsLock, IsFirst=1,LockDate=@LockDate,LastErrorDate=@LastErrorDate WHERE LoginName=@LoginName",
                    isLock ? 1 : 0, DateTime.Now, DateTime.MinValue, loginName);
            }
            catch (Exception e)
            {
                Log.Error("锁定/解锁 用户失败:{0}", e, "UPDATE UserExtend SET IsLock=@IsLock, IsFirst=true,LockDate=@LockDate,LastErrorDate=@LastErrorDate WHERE LoginName=@LoginName");
                throw  new BusinessException(LanguageManager.GetLanguageValue("ActionFail"));
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="isDelete"></param>
        /// <returns></returns>
        public static int DeleteUser(string loginName, bool isDelete)
        {
            IsDbExist();
            try
            {
                return SqliteHelper.ExecuteNonQuery(DbFile,
                    "UPDATE UserExtend SET IsDelete=@IsDelete, IsFirst=1,DeleteDate=@DeleteDate,LastErrorDate=@LastErrorDate WHERE LoginName=@LoginName",
                    isDelete ? 1 : 0, DateTime.Now, DateTime.MinValue, loginName);
            }
            catch (Exception e)
            {
                Log.Error("删除/恢复 用户失败:{0}", e, "UPDATE UserExtend SET IsDelete=@IsDelete, IsFirst=true,DeleteDate=@DeleteDate,LastErrorDate=@LastErrorDate WHERE LoginName=@LoginName");
                throw new BusinessException(LanguageManager.GetLanguageValue("ActionFail"));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="expire"></param>
        /// <returns></returns>
        public static int UpdateUserExpire(string loginName, DateTime expire)
        {
            IsDbExist();
            try
            {
                return SqliteHelper.ExecuteNonQuery(DbFile,
                    "UPDATE UserExtend SET  IsFirst=0,ExpiresDate=@ExpiresDate  WHERE LoginName=@LoginName",
                    expire, loginName);
            }
            catch (Exception e)
            {
                return -1;
            }
        }

        private static string GetSalt(int id)
        {
            var o = SqliteHelper.ExecuteScalar(DbFile, "SELECT Salt FROM User WHERE Id=@Id", id);
            if (o == null) return "";
            return o.ToString();
        }

        private static string GetSalt(string loginName)
        {
            var o = SqliteHelper.ExecuteScalar(DbFile, "SELECT Salt FROM User WHERE LoginName=@LoginName", loginName);
            if (o == null) return "";
            return o.ToString();
        }

        public static void UpdateErrorTime(string loginName, DateTime error)
        {
            var sql = "UPDATE UserExtend SET LastErrorDate=@LastErrorDate WHERE loginName=@loginName";
            try
            {
                SqliteHelper.ExecuteNonQuery(DbFile, sql, error, loginName);
            }
            catch (Exception e)
            {
                Log.Error("更新{0}密码输入错误时间失败：{1}", e, loginName, sql);
            }
        }

        private static void UpdateLoginTime(string loginName)
        {
            Log.Debug("记录{0}的登录时间", loginName);
            var sql = "UPDATE UserExtend SET LastDate=@LastDate,LastErrorDate=@LastErrorDate WHERE loginName=@loginName";
            try
            {
                SqliteHelper.ExecuteNonQuery(DbFile, sql, DateTime.Now, DateTime.MinValue, loginName);
            }
            catch (Exception e)
            {
                Log.Error("更新{0}登录时间失败：{1}", e, loginName, sql);
            }
        }

        public static void UpdateExpireTime(string loginName, int m)
        {
            Log.Debug("记录{0}的登录时间", loginName);
            var sql = "UPDATE UserExtend SET ExpiresDate=@ExpiresDate,IsFirst=0 WHERE loginName=@loginName";
            try
            {
                SqliteHelper.ExecuteNonQuery(DbFile, sql, DateTime.Now.AddMonths(m), loginName);
            }
            catch (Exception e)
            {
                Log.Error("更新{0}登录时间失败：{1}", e, loginName, sql);
            }
        }
    }
}
